from sqlalchemy import create_engine, Column, Integer, String, Sequence
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import declarative_base
# 创建一个数据库引擎
engine = create_engine('sqlite:///example.db', echo=True)
# 创建一个基类
Base = declarative_base()
# 定义一个数据模型类
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = Column(String(50))
    age = Column(Integer)
# 创建表格
Base.metadata.create_all(engine)
# 创建一个会话
Session = sessionmaker(bind=engine)
session = Session()
# 新增数据
new_user = User(name='John Doe', age=30)
session.add(new_user)
session.commit()
# 查询数据
query_result = session.query(User).filter_by(name='John Doe').first()
print(f"Query Result: {query_result.name}, {query_result.age}")
# 修改数据
query_result.age = 31
session.commit()
updated_result = session.query(User).filter_by(name='John Doe').first()
print(f"Updated Result: {updated_result.name}, {updated_result.age}")
# 删除数据
session.delete(updated_result)
session.commit()
deleted_result = session.query(User).filter_by(name='John Doe').first()
print(f"Deleted Result: {deleted_result}")
